package top.xzxsrq.fileviewutils.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xzxsrq.fileviewutils.entity.SysUser;
import top.xzxsrq.fileviewutils.entity.SysUserSearch;
import top.xzxsrq.fileviewutils.entity.SysUserWithRole;
import top.xzxsrq.fileviewutils.entity.TokensAreDiscarded;
import top.xzxsrq.fileviewutils.enums.AuthEnum;
import top.xzxsrq.fileviewutils.enums.RoleEnum;
import top.xzxsrq.fileviewutils.mapper.TokensAreDiscardedMapper;
import top.xzxsrq.fileviewutils.service.UserService;
import top.xzxsrq.web.utils.AjaxResult;
import top.xzxsrq.web.utils.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

//    @Autowired
//    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    @Autowired
    private TokensAreDiscardedMapper tokensAreDiscardedMapper;

//    @PostMapping("/login") // 放这里 JWTAuthenticationFilter super.setFilterProcessesUrl("/user/login");
//    public Result login(@RequestBody SysUser sysUser) {
//        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
//        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
//        if(authenticate.isAuthenticated()){
//            User user = (User) authenticate.getPrincipal();
//            // 从User中获取权限信息
//            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
//            // 创建Token
//            String token = JwtTokenUtil.createToken(user.getUsername(), authorities.toString());
//            Map<String, String> su = new HashMap<>();
//            su.put("token", JwtTokenUtil.TOKEN_PREFIX + token);
//            return Result.success(su);
//        } else {
//            return Result.failure();
//        }
//    }

    @PostMapping("getInfo")
    public AjaxResult getInfo() {
        return userService.getInfo();
    }

    @PostMapping("login_code")
    public AjaxResult login_code() {
        return AjaxResult.success();
    }

    @PostMapping("logout")
    public AjaxResult logout(HttpServletRequest request) {
        // token没办法重新设置，所以要失效token就要记录已经失效的token，已经退出的token拦截不再使用
        String tokenHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        // 去掉前缀 获取Token字符串
        String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        if (!JwtTokenUtil.isExpiration(token)) {
            Date endTime = JwtTokenUtil.getEndTime(token);
            TokensAreDiscarded tokensAreDiscarded = new TokensAreDiscarded();
            tokensAreDiscarded.setToken(token);
            tokensAreDiscarded.setEntTime(endTime);
            tokensAreDiscardedMapper.insert(tokensAreDiscarded);
        }
        SecurityContextHolder.clearContext();
        return AjaxResult.success("退出完成");
    }

    @PostMapping("updatePassword")
    public AjaxResult updatePassword(String oldPassword, String newPassword) {
        return userService.updatePassword(oldPassword, newPassword);
    }

    @PreAuthorize("hasAnyRole('initAdmin')")
    @PostMapping("resetInitPassword")
    public AjaxResult resetInitPassword(String newPassword) {
        return userService.resetInitPassword(newPassword);
    }
    @PreAuthorize("hasAnyRole('admin','initAdmin')")
    @PostMapping("resetPassword")
    public AjaxResult resetPassword(String username, String newPassword) {
        return userService.resetPassword(username, newPassword);
    }

    @PreAuthorize("hasAnyRole('admin','initAdmin')")
    @PostMapping("userList")
    public AjaxResult userList(@RequestBody SysUserSearch userSearch, int pageNum, int pageSize) {
        return userService.userList(userSearch,pageNum,pageSize);
    }

    @PreAuthorize("hasAnyRole('admin','initAdmin')")
    @PostMapping("addUser")
    public AjaxResult addUser(@RequestBody SysUserWithRole sysUserWithRole) {
        return userService.addUser(sysUserWithRole);
    }

    @PreAuthorize("hasAnyRole('admin','initAdmin')")
    @PostMapping("updateUser")
    public AjaxResult updateUser(@RequestBody SysUser sysUser) {
        return userService.updateUser(sysUser);
    }

    @PreAuthorize("hasAnyRole('admin','initAdmin')")
    @PostMapping("delUser")
    public AjaxResult delUser(String userId) {
        return userService.delUser(userId);
    }

    @PreAuthorize("hasAnyRole('admin','initAdmin')")
    @PostMapping("getUserById")
    public AjaxResult getUserById(String userId) {
        return userService.getUserById(userId);
    }

    @PostMapping("getRoleList")
    public AjaxResult getRoleList() {
        List<String> collect = Arrays.stream(RoleEnum.values()).map(Enum::name).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    @PostMapping("getAuthList")
    public AjaxResult getAuthList() {
        List<Map<String,String>> collect = Arrays.stream(AuthEnum.values()).map(i -> {
            Map<String,String> map = new HashMap<>();
            map.put("value",i.name());
            map.put("label",i.getLabel());
            return map;
        }).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    @PostMapping("updateUserSysConfig")
    public AjaxResult updateUserSysConfig(@RequestBody String userSysConfig) {
        return userService.updateUserSysConfig(userSysConfig);
    }
}
